﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jim.Core;

public class SdkDictionary : Dictionary<string, string>
{
    private const string DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public SdkDictionary() { }
    public SdkDictionary(IDictionary<string, string> dictionary):base(dictionary){}

    /// <summary>
    /// 添加一个新的键值对。空键或者空值的键值对将会被忽略。
    /// </summary>
    /// <param name="key">键名称</param>
    /// <param name="value">键对应的值，目前支持：string, int, long, double, bool, DateTime类型</param>
    public new void Add(string key, object value)
    {
        if (key.IsNullOrEmpty()) return;
        string strValue = string.Empty;
        if (value == null) return;
        if (value.IsCommonType()) strValue = value.ToString();
        else if (value is DateTime dt) strValue = dt.ToString(DATE_TIME_FORMAT);
        else
        {
            // 忽略 null 值的序列化器设置
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                DateFormatString = DATE_TIME_FORMAT
            };
            strValue = JsonConvert.SerializeObject(value,settings);
        }
        //string  urlEncodeSt= HttpUtility.UrlEncode(strValue, Encoding.UTF8);
        base.Add(key, strValue);
    }

    public void AddAll(IDictionary<string, string> dict)
    {
        if (dict != null && dict.Count > 0)
        {
            IEnumerator<KeyValuePair<string, string>> kvps = dict.GetEnumerator();
            while (kvps.MoveNext())
            {
                KeyValuePair<string, string> kvp = kvps.Current;
                Add(kvp.Key, kvp.Value);
            }
        }
    }
}
